import axios from "axios";
import { ElMessage } from "element-plus";
import { userUserStore } from "@/pinia/user";
import { router } from "@/router";

const http = axios.create({
	baseURL: "/api",
	timeout: 5000,
});

http.interceptors.request.use((config) => {
	const USER = userUserStore();

	if (USER.user_info?.token) {
		config.headers["token"] = USER.user_info.token;
	}

	return config;
});

http.interceptors.response.use((response) => {
	if (response.status == 200) {
		const code = response.data.code;
		if (code == 1000) {
			return response.data;
		} else if (code == 9002) {
			router.replace("/login");
			ElMessage.error("登录已失效，请重新登录");
		} else {
			ElMessage.error(response.data.msg);
		}
	}
});

interface ResponseData {
	code: number;
	msg: string;
	data: any;
}

export default {
	post(...params: any[]): Promise<ResponseData> {
		return http.post.apply(null, params as any) as Promise<ResponseData>;
	},
};
